﻿//+------------------------------------------------------------------------------------------------------------------------------------------------------
//
//Description: String helper.
//Author: Aravind Ramarathinam (aravr@microsoft.com)
//Copyright © Microsoft Corporation
//Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
//You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
//
//THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, 
//INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 
//See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
// 
//--------------------------------------------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace VmroleAuthor.Helpers
{
    public static class StringHelper
    {
        private static readonly string RegexEscapedNewline = Regex.Escape("\n");
        private static readonly string RegexEscapedRightBracket = Regex.Escape("}");
        private const string RtfRightBracket = @"\}";
        private const string RtfNewline = @"\par ";
       
     

        /// <summary>
        /// This API takes an unescaped RTF string and it makes it unicode compliant
        /// This means that for every character that cannot be represented in an RTF control
        /// today, we change it to its numeric representation and we make it 16 bits (the
        /// extra "?" is adding the second byte to the representation). Now, with this
        /// encoding the RTF control can propertly display this.
        /// BUGFIX 18554
        /// </summary>
        /// <param name="unescapedRtfString">A string containing RTF markers which may also have UNICODE characters that need hex encoding</param>
        /// <returns></returns>
        public static string EscapeForUnicodeRtf(string unescapedRtfString)
        {
            StringBuilder unicodeString = new StringBuilder();
            foreach (char ch in unescapedRtfString)
            {
                int numericRepresentation = ch;
                if (numericRepresentation <= 127)
                {
                    unicodeString.Append(ch);
                }
                else
                {
                    unicodeString.AppendFormat(@"\u{0}?", numericRepresentation);
                }
            }
            return unicodeString.ToString();
        }

        /// <summary>
        /// Format a list of parameters for user display, e.g.
        /// {1,2,3} -> "1, 2, 3"
        /// </summary>
        /// <param name="parameterStrings"></param>
        /// <returns></returns>
        public static string ListToCommaSeparatedString(IEnumerable<string> parameterStrings)
        {
            string separator = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator;
            return StringHelper.FormatParameterListUsingDelimiter(parameterStrings, string.Format("{0} ", separator));
        }

        /// <summary>
        /// Format a list of parameters for user display without spaces between separator and next element. 
        /// Useful where number of characters are limited for certain wmi calls etc.
        /// {1,2,3} -> "1,2,3"
        /// </summary>
        /// <param name="parameterStrings"></param>
        /// <returns></returns>
        public static string ListToCommaSeparatedStringWithoutSpaces(IEnumerable<string> parameterStrings)
        {
            string separator = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator;
            return StringHelper.FormatParameterListUsingDelimiter(parameterStrings, string.Format("{0}", separator));
        }

        /// <summary>
        /// escapes Rtf-unprintable characters but leaves newline.
        /// This method should only be used when you do not expect the string to contain newline.
        /// </summary>
        /// <param name="unescapedString">original string</param>
        /// <returns>Rtf-safe string</returns>
        public static string EscapeForRtfWithoutNewline(string unescapedString)
        {
            string rtfString = Regex.Escape(unescapedString);
            rtfString = rtfString.Replace(StringHelper.RegexEscapedRightBracket,
                StringHelper.RtfRightBracket);
            rtfString = EscapeForUnicodeRtf(rtfString);
            return rtfString;
        }

        /// <summary>
        /// escapes Rtf-unprintable characters.
        /// </summary>
        /// <param name="unescapedString">original string</param>
        /// <returns>Rtf-safe string</returns>
        public static string EscapeForRtf(string unescapedString)
        {
            string rtfString = StringHelper.EscapeForRtfWithoutNewline(unescapedString);
            rtfString = rtfString.Replace(StringHelper.RegexEscapedNewline,
                StringHelper.RtfNewline);
            return rtfString;
        }

        /// <summary>
        /// Take a list, sort it in a consistant manner and convert it to a comma separated
        /// string.  {a,d,c,b} -> "a, b, c, d"
        /// </summary>
        /// <param name="parameterStrings"></param>
        /// <returns></returns>
        public static string ListToSortedCommaSeparatedString(List<string> parameterStrings)
        {
            parameterStrings.Sort();
            return StringHelper.ListToCommaSeparatedString(parameterStrings);
        }

        /// <summary>
        /// This method converts a list of string items into a 'delimeter' separated string.
        /// E.g. {a,b,c,d} with "|" as delimiter ==> a|b|c|d
        ///      {a,b,c,d} with ", " as delimiter ==> a, b, c, d
        /// If any of the items in the array is empty or null string, this method would skip them.
        /// E.g. {a,null,c} with "|" ==> a|c
        /// Usages:
        /// a) It could be use to format virtual machine names e.g. "vm-1, vm2, vm-xp-3" to show on UI.
        /// b) It could be used to generate pipe separated monad command line input parameter list.
        ///
        /// NOTE: Please specify a delimiter included in the resources if you are planning to show the string on the UI.
        /// This would avoid any localization issues.
        /// </summary>
        public static string FormatParameterListUsingDelimiter(IEnumerable<string> items, string delimiter)
        {
            StringBuilder builder = new StringBuilder();

            if (items != null)
            {
                foreach (string item in items)
                {
                    if (string.IsNullOrEmpty(item))
                    {
                        continue;
                    }

                    if (builder.Length > 0)
                    {
                        builder.Append(delimiter);
                    }
                    builder.Append(item.Trim());
                }
            }

            return builder.ToString();
        }

      

        /// <summary>
        /// Determines if the given pattern is contained as a substring in any of the input objects.
        /// The goal is to avoid comparing to all the strings and to avoid converting the objects
        /// to strings if a match is found earlier in the comparison.
        /// </summary>
        /// <param name="pattern"></param>
        /// <param name="values"></param>
        /// <returns></returns>
        public static bool CaseInsensitiveMatchAny(string pattern, params object[] values)
        {
            bool matches = false;
            for (int i = 0; !matches && i < values.Length; ++i)
            {
                if (values[i] != null)
                {
                    string s = values[i] as string;
                    if (s == null)
                    {
                        s = values[i].ToString();
                    }
                    matches = s.IndexOf(pattern, System.StringComparison.CurrentCultureIgnoreCase) >= 0;
                }
            }
            return matches;
        }

        /// <summary>
        /// Invariant ignore case version of FindMatchingLengthFromHead
        /// </summary>
        public static int FindMatchingLengthFromHeadIgnoreCaseInvariant(string str1, string str2)
        {
            return FindMatchingLengthFromHead(str1.ToLowerInvariant(), str2.ToLowerInvariant());
        }

        /// <summary>
        /// Invariant ignore case version of FindMatchingLengthFromEnd
        /// </summary>
        public static int FindMatchingLengthFromEndIgnoreCaseInvariant(string str1, string str2)
        {
            return FindMatchingLengthFromEnd(str1.ToLowerInvariant(), str2.ToLowerInvariant());
        }

        /// <summary>
        /// Return the length of the matching character of the two strings from the head
        /// In case one starts with another, returns the length of the shorter one
        /// </summary>
        /// <param name="str1">string 1</param>
        /// <param name="str2">string 2</param>
        /// <returns>Return the length of the matching character of the two strings from the head
        /// In case one starts with another, returns the length of the shorter one</returns>
        public static int FindMatchingLengthFromHead(string str1, string str2)
        {
            if (string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2))
            {
                return 0;
            }

            char a = str1[0];
            char b = str2[0];
            int minLength = Math.Min(str1.Length, str2.Length);

            int length = 0;
            while (a == b)
            {
                length = length + 1;
                if (length == minLength)
                {
                    break;
                }

                a = str1[length];
                b = str2[length];
            }

            return length;
        }

        /// <summary>
        /// Return the length of the matching character of the two strings from the end
        /// In case one ends with another, returns the length of the shorter one
        /// </summary>
        /// <param name="str1">string 1</param>
        /// <param name="str2">string 2</param>
        /// <returns>Return the length of the matching character of the two strings from the end
        /// In case one ends with another, returns the length of the shorter one</returns>
        public static int FindMatchingLengthFromEnd(string str1, string str2)
        {
            if (string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2))
            {
                return 0;
            }

            int length1 = str1.Length;
            int length2 = str2.Length;

            char a = str1[length1 - 1];
            char b = str2[length2 - 1];

            int minLength = Math.Min(str1.Length, str2.Length);

            int length = 0;
            while (a == b)
            {
                length = length + 1;
                if (length == minLength)
                {
                    break;
                }

                a = str1[length1 - 1 - length];
                b = str2[length2 - 1 - length];
            }

            return length;
        }
        

        /// <summary>
        /// Appends the back slash to the given path.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns>Path with trailing backslash; Null if path is null</returns>
        public static string AppendBackslash(string path)
        {
            if (path == null)
            {
                return null;
            }

            if (path.EndsWith(@"\") == false)
            {
                return (path + @"\");
            }

            return path;
        }

        /// <summary>
        /// Returns the trimmed string or empty if <para>arg</para> is <code>null</code>
        /// </summary>
        /// <param name="arg">string to be trimmed</param>
        /// <returns>String.Empty if null</returns>
        public static string SafeTrim(string arg)
        {
            return arg == null ? string.Empty : arg.Trim();
        }

        /// <summary>
        /// Returns the trimmed string or empty if <para>arg</para> is <code>null</code>
        /// </summary>
        /// <param name="arg">string to be trimmed</param>
        /// <returns>String.Empty if null</returns>
        public static string TrimSafe(this string arg)
        {
            return StringHelper.SafeTrim(arg);
        }

        /// <summary>
        /// Returns true if <para>arg</para> contains any whitespace characters.
        /// </summary>
        /// <param name="arg">string to examine for whitespace characters</param>
        /// <returns></returns>
        public static bool ContainsWhiteSpace(this string arg)
        {
            return arg.Any(char.IsWhiteSpace);
        }

        /// <summary>
        /// Format a "number nouns" style string with special cases to separately localize zero and one.
        /// </summary>
        /// <param name="count">The quantity</param>
        /// <param name="zero">String to use for zero</param>
        /// <param name="one">String to use for one</param>
        /// <param name="twoOrMore">String format to use for two or more</param>
        public static string FormatQuantity(int count, string zero, string one, string twoOrMore)
        {
            string result;
            if (count == 0)
            {
                result = zero;
            }
            else if (count == 1)
            {
                result = one;
            }
            else
            {
                result = String.Format(twoOrMore, count);
            }
            return result;
        }

        /// <summary>
        /// This method returns  a base64 encoded string
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string GetBase64EncodedString(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input;
            }
            byte[] asBytes = System.Text.Encoding.UTF8.GetBytes(input);
            string base64String = System.Convert.ToBase64String(asBytes);
            return base64String;
        }

        /// <summary>
        /// Joins strings in the list delimited by the character supplied
        /// </summary>
        /// <param name="stringsToJoin"></param>
        /// <param name="delimiter"></param>
        /// <returns></returns>
        public static string JoinStringsWithDelimiter(List<string> stringsToJoin, char delimiter)
        {
            StringBuilder joinedString = new StringBuilder("");
            if (stringsToJoin.Count == 0)
            {
                return joinedString.ToString();
            }
            foreach (string astring in stringsToJoin)
            {
                joinedString.Append(astring);
                joinedString.Append(delimiter);
            }
            if (joinedString.Length == 0)
            {
                return joinedString.ToString();
            }
            joinedString = joinedString.Remove(joinedString.Length - 1, 1);
            return joinedString.ToString();
        }
       
    } 
}
